/********************************************************************
	created:	2012/02/26   20:31
	filename: 	hy_net_module.h
	author:		zxh
	
	purpose:	
*********************************************************************/
#ifndef _HY_NET_MODULE_H_
#define _HY_NET_MODULE_H_

#include <vector>

#include "hy_msg.h"
#include "hy_server_base.h"
#include "hy_session.h"
#include "hy_acceptor.h"
#include "hy_pool.h"
#include "hy_reactor.h"


typedef hy_msg_pool	block_pool_t;

class hy_net_module : public hy_module_base
{
	typedef hy_net_module hy_session_service_t;
public:
	hy_net_module(){}
	~hy_net_module(){}

	virtual hy_err_t init()
	{
		_reactor = new hy_reactor();
		_reactor->init();
		return hy_right;
	}

	virtual hy_err_t unit()
	{
		return hy_right;
	}

	block_pool_t get_block_pool()
	{
		return _blocks;
	}

	virtual void recycle_link(hy_i64_t id)
	{
		hy_lock lock(_slock);
		hy_assert(_sessions[id]->id() == id);
		delete _sessions[id];
		_sessions.erase(id);
	}

	virtual hy_err_t send_block(hy_i64_t scid, hy_msg* buff)
	{
		hy_lock lock(_slock);
		if (_sessions.find(scid) != _sessions.end())
		{
			hy_session* session = _sessions[scid];
			session->send(buff);
			return hy_right;
		}
		buff->reference(false);
		return hy_error;
	}



	hy_err_t add_session(const char* ipaddr, hy_u32_t port,hy_session* session)
	{
		session->conn(ipaddr,port);

		hy_lock lock(_slock);
		_sessions[session->id()] = session;
		return hy_right;
	}

	void run()
	{
		_reactor->run();
	}


	void stop()
	{
		_reactor->stop();
	}

protected:
	block_pool_t						_blocks;
	hy_mutex							_slock;
	std::map<hy_i64_t,hy_session*>		_sessions;
	hy_reactor*							_reactor;
	std::vector<hy_acceptor*>			_acceptors;
};


#endif  //_HY_NET_MODULE_H_
